class EventsController < ApplicationController

  before_filter :set_nav_session
  before_filter :login_required, :except => [:index, :show, :all, :category]
  before_filter :unread_messages_amount, :only => [:index, :all, :category, :show, :new, :edit,
                                                   :new_pic, :choice_school]
  def index
    #build_events(["events.end_at > now()"])
    # @events = Event.recent
    @events = Event.paginate(:page => params[:page],
                             :conditions => ["end_at > ?", Time.now],
                             :per_page   => 10, 
                             :order => "events.created_at desc")
    @categories_count = Event.find_by_sql("select category, count(*) as count from events group by category")
    @participations = Participation.recent_join
    
    @comments = EventComment.all
    
    if logged_in?
      @my_joineds = Participation.events_joined_by(current_user)
    end
=begin    
    @comments = EventComment.find(:all, :limit => 10, :order => "event_comments.created_at desc", :include => [:user, :event])
    @photos = Photo.find(:all, :conditions => "photos.event_id<>0", 
                               :include => :event,
                               :limit => 10,
                               :order => "photos.created_at desc")
=end
  end
  
  def all
    build_events()
  end
  
  def category
    build_events(["events.category=?", params[:cat].to_i])
  end
  
  def show
    @event = Event.find(params[:id])
    @comments = @event.comments
    @comment = EventComment.new
    @photos = @event.photos
    #store_location
  end
  
  def new
    @event = Event.new(:ref => params[:ref])
  end
  
  def create
    @event = Event.new(params[:event])
    @event.submitor = current_user
    @event.save!
    flash[:notice] = "你刚刚发布了一个活动"
    redirect_back_or_default(event_path(@event))
  rescue ActiveRecord::RecordInvalid
    render :action => 'new'
  end
  
  def edit
    @event = Event.find(params[:id])
  end
  
  def update
    @event = Event.find(params[:id])
    @event.editable_by?(current_user) || access_denied
    @event.update_attributes!(params[:event])
    flash[:notice] = "您刚刚编辑了活动信息"
    redirect_back_or_default(event_path(@event))
  rescue ActiveRecord::RecordInvalid
    render :action => 'edit'
  end
  
  def destroy
    @event = Event.find(params[:id])
    @event.editable_by?(current_user) || access_denied
    @event.destroy
    flash[:notice] = "#{@event.title}活动已经删除"
    redirect_back_or_default(events_url)
  end
  
  def new_pic
    @event_pic = EventPic.new
    @event = Event.find(params[:id])
  end
  
  def create_pic
    @event = Event.find(params[:id])
    @event_pic = EventPic.new(params[:event_pic])
    @event_pic.event = @event
    @event_pic.save!
    flash[:notice] = "您上传了活动图片"
    redirect_back_or_default(event_path(@event))
  end
  
  def join
    @participation = Participation.find(:first, :conditions => {:event_id => params[:id], :user_id => current_user.id})
    if @participation # each user can join the event once
      flash[:notice] = "您已经参加了这个活动"
      redirect_back_or_default(event_path(params[:id]))
    else
      @event = Event.find(params[:id])
      @participation = Participation.new
      @participation.event = @event
      @participation.user = current_user
      @participation.save!
      flash[:notice] = "您要参加这个活动"
      redirect_back_or_default(event_path(@event))
    end
  end
  
  # quit event
  def quit
    @event = Event.find(params[:id])
    @participation = Participation.find(:first, :conditions => {:user_id => current_user.id,
                                                                :event_id => @event.id})
    @participation.destroy
    redirect_back_or_default(event_path(@event))
  end
  
  # get school list, let user select which school is going to visit on 1kg more trip
  def choice_school
    @event = Event.find(params[:id])
    @provinces, @output = sort_by_province
  end
  
  def add_school
    @event = Event.find(params[:id])
    @school = School.find(params[:school_id])
    @event.school = @school
    @event.save!
    flash[:notice] = "#{@event.title}要去#{@school.id}"
    redirect_back_or_default(event_url(@event.id))
  end
    
  def latest_comments
    @event = Event.find(params[:id])
    @comments = @event.comments.find(:all, 
                                    :limit => 3, 
                                    :order => "event_comments.created_at desc", 
                                    :include => [:user])
    render :layout => false # for thickbox
  end  
    
  private
  def build_events(conditions = "1=1")
    @events = Event.paginate(:page => params[:page] || 1,
                             :conditions => conditions,
                             :order => "events.created_at desc",
                             :include => [:submitor, :school, :pic])
    @categories_count = Event.find_by_sql("select category, count(*) as count from events group by category")
    @participations = Participation.recent_join
  end
  
  def sort_by_province
    provinces = Area.roots
    all_provinces = []
    output = []
    provinces.each do |province|
      areas = province.all_children
      unless areas.empty?
        schools = School.find(:all, 
                              :conditions => ["schools.is_hidden=? and schools.area_id in (?)", false, areas], 
                              :joins => "left join users on schools.submitor_id = users.id",
                              :select => "schools.id, schools.title, schools.updated_at, schools.is_validate,
                                          schools.title, schools.submitor_id, users.login",
                              :order => "schools.area_id asc, schools.created_at desc")
        unless schools.empty?
          output[province.id] = schools
        end
      end
    end
    provinces.each do |province|
      unless output[province.id].blank?
        all_provinces << province
      end
    end
    
    return all_provinces, output
  end
  
  def set_nav_session
    session[:nav] = "events"
  end
end
